import { _decorator, Component, Node, Prefab, instantiate, Camera, find, Vec3 } from "cc";
import { UserInfo } from "../../prefabs/game/UserInfo";
import event from "../../utils/event";
import websocket from "../../utils/websocket";
const { ccclass, property } = _decorator;

@ccclass("Game/Controller/UserInfoPanel")
export class UserInfoPanel extends Component {
    @property(Prefab)
    private userInfoPrefab: Prefab = null;
    @property(Camera)
    private mainCamera: Camera = null;

    private userInfo = null;
    private userInfoList: Node[] = [];

    start() {
        this.mainCamera = find("Main Camera").getComponent(Camera);
        event.on("game::userinfo", this.onUserInfo, this);
        event.on("ui::userinfopos", this.onUserInfoPosSync, this);
        websocket.on("game::enter", this.onGameEnter, this);
        websocket.on("player::create", this.onPlayerCreate, this);
        websocket.on("talk", this.onTalk, this);
    }

    onDestroy() {
        event.off("game::userinfo");
        websocket.off("game::enter");
        websocket.off("player::create");
        websocket.off("player::sync");
    }

    onUserInfo(data) {
        this.userInfo = data;
    }

    onUserInfoPosSync(arr) {
        for (const { userId, pos } of arr) {
            const userInfo = this.userInfoList.find((item) => item.getComponent(UserInfo).userId === userId);
            if (userInfo) {
                this.mainCamera.convertToUINode(pos, this.node, pos);
                userInfo.getComponent(UserInfo).sync(pos);
            }
        }
    }

    onGameEnter(data) {
        for (const playerData of data) {
            this.onPlayerCreate(playerData);
        }
    }

    onPlayerCreate(data) {
        const { userId, pos, euler } = data;
        const userInfo = instantiate(this.userInfoPrefab);

        // userInfo.active = false;
        userInfo.getComponent(UserInfo).init(data, userId === this.userInfo.userId);

        this.userInfoList.push(userInfo);
        this.node.addChild(userInfo);
    }

    onTalk(data) {
        const userInfo = this.userInfoList.find((item) => item.getComponent(UserInfo).userId === data.userId);
        if (userInfo) {
            userInfo.getComponent(UserInfo).talk(data.msg);
        }
    }

    // onPlayerSync(data) {
    //     for (const item of data) {
    //         const userInfo = this.userInfoList.find((_) => _.getComponent(UserInfo).userId === item.userId);
    //         if (userInfo) {

    //             userInfo.getComponent(UserInfo).sync(pos);
    //             // const userInfo = this.userInfoList.find((_) => _.getComponent(UserInfo).userId === item.userId);
    //             // userInfo.getComponent(UserInfo).sync(pos);
    //         }
    //     }
    // }
}
